// #ifdef H5
import wx from '@/utils/weixin-js-sdk/index.js'
// #endif
// #ifndef VUE3
import Vue from 'vue'
import App from './App'
import {get,post,put,BASE_URL,ENV,sassAppId,channel} from './network/http'
import {toast,getUrlParam, throttle} from '@/utils/Tools.js'
import uView from '@/uni_modules/uview-ui'

const sourceUrl = 'https://fine-yahe.oss-cn-shanghai.aliyuncs.com'
let mpAppid = 'wx28364debdead316c'
// #ifdef MP-TOUTIAO
mpAppid = 'tt9fbae9070086fe8601'
// #endif
// #ifdef H5
mpAppid = 'wx7cf1fd5ea653f3c4'
// #endif
Vue.prototype.$get = get
Vue.prototype.$post = post
Vue.prototype.$put = put
Vue.prototype.BASE_URL = BASE_URL
Vue.prototype.$sassAppId = sassAppId
Vue.prototype.$channel = channel
Vue.prototype.$toast = toast
Vue.prototype.$sourceUrl = sourceUrl
Vue.prototype.$mpAppid = mpAppid
Vue.prototype.$throttle = throttle


Vue.prototype.getMedia = (pic)=>{
  const url = pic?(pic.includes('http')?pic:sourceUrl + pic):'';
  return url
}
Vue.use(uView);

Vue.config.productionTip = false

uni.warrantLogin = async function() {
  const {code} = getUrlParam(location.href)
  if(uni.getStorageSync('openID')) return;
  if(!code){
    const redirect_uri = `https://wxgateway.ant.shop/?env=${ENV}&from=wechat_redirect`;
    location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${mpAppid}&redirect_uri=` + encodeURIComponent(redirect_uri) + '&response_type=code&scope=snsapi_base&state=1';
    return;
  }
  let data = {
    loginType:'WECHAT',
    username: mpAppid,
    password:code
  }
  // #ifdef MP-TOUTIAO
  data = {
    loginType:'TOUTIAO',
    username: mpAppid,
    password:code
  }
  // #endif
  this.$post('/yahe/login',data,'1').then(res=>{
    if(res.code === '1'){
      uni.setStorageSync('openID',res.content.openId)
    }
  })
}

uni.wxsdk = async function(url){
	const ret = await this.$post('/mb/third/wx/getSignature',{"appId":mpAppid,"url":url || location.href.split('#')[0]})
	if(ret.code === '1'){
		wx.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: ret.content.appId, // 必填，公众号的唯一标识
				timestamp: ret.content.timestamp+'', // 必填，生成签名的时间戳
				nonceStr: ret.content.nonceStr, // 必填，生成签名的随机串
				signature: ret.content.signature,// 必填，签名
				jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage','hideMenuItems','showMenuItems','hideAllNonBaseMenuItem','hideOptionMenu','chooseWXPay','openLocation'] // 必填，需要使用的JS接口列表
		});
		return true;
	}else{
		return false
	}
}

uni.verifyLogin = () => { ///  判断是否登录
  if(!uni.getStorageSync('token') || uni.getStorageSync('userSource') !== 'USER'){
    uni.navigateTo({
      url:'/pages/other/login'
    })
    throw false;
  }
}
uni.handleLogin = (type)=>{
  // #ifdef H5
  let ua = navigator.userAgent.toLowerCase();  
  if(ua.match(/MicroMessenger/i)=="micromessenger") {
    uni.warrantLogin()
    return;
  }
  uni.navigateTo({
    url:'/pages/other/login/index'
  })
  return;
  // #endif
  uni.login({
    success:res=>{
      let loginType = 'WECHAT'
      // #ifdef MP-TOUTIAO
      loginType = 'DOUYIN'
      // #endif
      const data = {
        loginType,
        username: mpAppid,
        password:res.code
      }
      if (uni.getStorageSync('invite_uid')) {
        Object.assign(data, {
          salesMan: uni.getStorageSync('invite_uid')
        })
      }
      post('/yahe/login',data).then(res=>{
        if(res.code != '1'){
          toast(res.message)
          return;
        }
        const timestamp = new Date().getTime();
        uni.setStorageSync('user',{
          ...res.content,
          loginType,
          timestamp
        });
        uni.setStorageSync('openID',res.content.openId)
        uni.setStorageSync('userSource',res.content.userSource)
        uni.setStorageSync('token',res.content.token.accessToken)
        uni.$emit('updateLogin')
        if(type == 'back') uni.navigateBack()
      })
    }
  })
}
uni.getOpenId = async ()=>{
  return new Promise(resolve => {
    if(uni.getStorageSync('openID')){
      resolve(uni.getStorageSync('openID'))
    }else{
      // #ifdef H5
        resolve(uni.getStorageSync('openID'))
      // #endif
      // #ifdef MP
        let loginType = 'WECHAT'
        // #ifdef MP-TOUTIAO
        loginType = 'DOUYIN'
        // #endif
        uni.login({
          scopes:'auth_base',
          onlyAuthorize:false,
          success:res=>{
            post('/yahe/login',{
              loginType,
              username: mpAppid,
              password:res.code
            }).then(res=>{
              if(res.code === '1'){
                uni.setStorageSync('openID',res.content.openId)
                resolve(res.content.openId)
              }
            })
          }
        })
      // #endif
    }
  })
}

App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
import App from './App.vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif
